import win32security
import ntsecuritycon
import os
import sys
import win32net
import win32netcon
import win32wnet
import tempfile
import ctypes
from ctypes import wintypes

def is_admin():
    """检查是否以管理员权限运行"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def connect_to_share(remote_path, username, password):
    """
    连接到NAS共享盘
    """
    # net_resource = win32netcon.NETRESOURCE()
    # NETRESOURCE
    # net_resource.lpRemoteName = remote_path
    # net_resource.dwType = win32netcon.RESOURCETYPE_DISK
    
    # try:
    #     win32wnet.WNetAddConnection2(
    #         net_resource, password, username, 0
    #     )
    #     print(f"成功连接到共享: {remote_path}")
    #     return True
    # except Exception as e:
    #     print(f"连接失败: {str(e)}")
    #     return False

    """
    连接到NAS共享盘
    """
    # 创建NETRESOURCE结构
    net_resource = win32net.NETRESOURCE()
    net_resource.lpRemoteName = remote_path
    net_resource.dwType = win32netcon.RESOURCETYPE_DISK
    net_resource.lpLocalName = None
    net_resource.lpProvider = None
    
    try:
        # 连接到共享
        win32wnet.WNetAddConnection2(
            net_resource, password, username, 0
        )
        print(f"成功连接到共享: {remote_path}")
        return True
    except Exception as e:
        print(f"连接失败: {str(e)}")
        return False
    
def disconnect_from_share(remote_path):
    """
    断开NAS共享盘连接
    """
    try:
        win32wnet.WNetCancelConnection2(remote_path, 0, True)
        print(f"已断开连接: {remote_path}")
    except Exception as e:
        print(f"断开连接时出错: {str(e)}")

def get_file_security_info(file_path):
    """
    获取文件或文件夹的安全信息
    """
    try:
        # 获取文件的安全描述符
        sd = win32security.GetFileSecurity(
            file_path, win32security.DACL_SECURITY_INFORMATION
        )
        dacl = sd.GetSecurityDescriptorDacl()
        
        if dacl is None:
            print("没有找到DACL（自由访问控制列表）")
            return
        
        print(f"文件路径: {file_path}")
        print("权限信息:")
        print("-" * 50)
        
        # 遍历DACL中的每个ACE（访问控制条目）
        for ace_index in range(dacl.GetAceCount()):
            ace = dacl.GetAce(ace_index)
            ace_type, ace_mask, sid = ace
            
            # 获取账户名和域名
            try:
                account_name, domain, _ = win32security.LookupAccountSid(None, sid)
                full_name = f"{domain}\\{account_name}" if domain else account_name
            except:
                full_name = f"无法解析的SID: {sid}"
            
            # 获取权限类型
            if ace_type == win32security.ACCESS_ALLOWED_ACE_TYPE:
                access_type = "允许"
            elif ace_type == win32security.ACCESS_DENIED_ACE_TYPE:
                access_type = "拒绝"
            else:
                access_type = f"未知类型 ({ace_type})"
            
            # 解析权限掩码
            permissions = []
            if ace_mask & ntsecuritycon.FILE_READ_DATA:
                permissions.append("读取数据")
            if ace_mask & ntsecuritycon.FILE_WRITE_DATA:
                permissions.append("写入数据")
            if ace_mask & ntsecuritycon.FILE_APPEND_DATA:
                permissions.append("追加数据")
            if ace_mask & ntsecuritycon.FILE_READ_EA:
                permissions.append("读取扩展属性")
            if ace_mask & ntsecuritycon.FILE_WRITE_EA:
                permissions.append("写入扩展属性")
            if ace_mask & ntsecuritycon.FILE_EXECUTE:
                permissions.append("执行")
            if ace_mask & ntsecuritycon.FILE_READ_ATTRIBUTES:
                permissions.append("读取属性")
            if ace_mask & ntsecuritycon.FILE_WRITE_ATTRIBUTES:
                permissions.append("写入属性")
            if ace_mask & ntsecuritycon.DELETE:
                permissions.append("删除")
            if ace_mask & ntsecuritycon.READ_CONTROL:
                permissions.append("读取权限")
            if ace_mask & ntsecuritycon.WRITE_DAC:
                permissions.append("修改权限")
            if ace_mask & ntsecuritycon.WRITE_OWNER:
                permissions.append("取得所有权")
            if ace_mask & ntsecuritycon.SYNCHRONIZE:
                permissions.append("同步")
            if ace_mask & ntsecuritycon.FILE_ALL_ACCESS:
                permissions.append("完全控制")
            if ace_mask & ntsecuritycon.GENERIC_ALL:
                permissions.append("所有权限")
            
            print(f"用户/组: {full_name}")
            print(f"访问类型: {access_type}")
            print(f"权限: {', '.join(permissions) if permissions else '无明确权限'}")
            print("-" * 30)
            
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {str(e)}")

def get_credentials():
    """
    获取用户输入的凭据
    """
    username = input("请输入NAS用户名: ").strip()
    password = input("请输入NAS密码: ").strip()
    return username, password

def main():
    if not is_admin():
        print("警告: 建议以管理员权限运行此脚本以获得更准确的权限信息")
        print("请右键点击命令行或PowerShell，选择'以管理员身份运行'")
    
    if len(sys.argv) != 2:
        print("用法: python nas_permissions.py <NAS共享路径>")
        print("例如: python nas_permissions.py \"\\\\nas-server\\share\"")
        print("例如: python nas_permissions.py \"\\\\nas-server\\share\\folder\"")
        sys.exit(1)
    
    nas_path = sys.argv[1]
    
    # 获取共享根路径（用于连接）
    if "\\" in nas_path[2:]:
        share_root = "\\\\" + nas_path[2:].split("\\")[0]
    else:
        share_root = nas_path
    
    # 获取凭据
    username, password = get_credentials()
    
    # 连接到共享
    if not connect_to_share(share_root, username, password):
        print("无法连接到NAS共享，请检查凭据和网络连接")
        sys.exit(1)
    
    try:
        # 检查路径是否存在
        if not os.path.exists(nas_path):
            print(f"错误: 路径 '{nas_path}' 不存在")
            sys.exit(1)
        
        # 获取权限信息
        get_file_security_info(nas_path)
        
    finally:
        # 断开连接
        disconnect_from_share(share_root)

if __name__ == "__main__":
    main()